package org.example.exchange.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import org.example.RabbitMQUtils;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * (星号)可以代替一个位置
 * (井号)可以替代零个或多个位置
 * 当一个队列绑定键是 #，那么这个队列将接收所有数据，就有点像 fanout 了
 * 如果队列绑定键当中没有 # 和 * 出现，那么该队列绑定类型就是 direct 了
 * @description: topic交换主题及其相关队列
 * @author: WangBlue
 * @create: 2023-11-29 20:57
 **/
public class ConsumerReceiveLogsTopic02 {
    //交换机的名称
    public static final String EXCHANGE_NAME = "topic_logs";

    //接收消息
    public static void main(String[] args) throws IOException, TimeoutException {
        Channel channel = RabbitMQUtils.getChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        //声明队列
        String queueName = "Q2";
        // 声明队列
        // channel.queueDeclare(队列名/String, 持久化/boolean, 共享消费/boolean, 自动删除/boolean, 配置参数/Map);
        channel.queueDeclare(queueName,false,false,false,null);

        /**
         * 绑定交换机与队列,
         * 队列为：queueName,
         * 交换机：EXCHANGE_NAME， 路由键：*.*.rabbit、"lazy.#
         */
        channel.queueBind(queueName,EXCHANGE_NAME,"*.*.rabbit");
        channel.queueBind(queueName,EXCHANGE_NAME,"lazy.#");
        System.out.println("等待接收消息...");

        DeliverCallback deliverCallback = (consumerTag, message) -> {
            System.out.println(new String(message.getBody(),"UTF-8"));
            System.out.println("接收队列："+queueName+"  绑定键:"+message.getEnvelope().getRoutingKey());
        };
        //接收消息
        /**
         * 消费者消费消息
         * 1.消费哪个队列
         * 2.消费成功之后是否要自动应答true：代表自动应答false:代表手动应答
         * 3.消费者未成功消费的回调
         * 4.消费者取消消费的回调
         */
        channel.basicConsume(queueName,true,deliverCallback,consumerTag ->{});
    }
}
